// 创建APP
const express = require('express');
const app = express();
const expressWs = require('express-ws');
expressWs(app);

const aWss = expressWs(app).getWss()

app.ws('/', (ws, req, next) => {

    let auth = req.headers['sec-websocket-protocol']
    if (!auth) {
        ws.send('无效链接');
    }
    ws.id = auth;
    ws.send('建立链接' + auth);

    ws.on('message', (msg) => {
        console.log(aWss.clients)
        aWss.clients.forEach((client) => {
            console.log(JSON.parse(msg).to)
            console.log(JSON.parse(msg).to.includes('-'))
            if (JSON.parse(msg).to.includes('-' + client.id + '-') || client.id == ws.id) {
                client.send(JSON.parse(msg).msg)
            }
        })
    });

    ws.on('close', () => {
        console.log('关闭连接')
    });
});
app.listen(3000, () => {
    console.log('启动成功')
});